package com.example.fragment.library.common.fragment

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import com.example.fragment.library.base.bus.SharedFlowBus
import com.example.fragment.library.base.fragment.BaseFragment
import com.example.fragment.library.common.activity.RouterActivity
import com.example.fragment.library.common.bean.UserBean

open class RouterFragment : BaseFragment() {

    /**
     * 获取baseActivity方便调用navigation方法进行页面切换
     */
    lateinit var baseActivity: RouterActivity
    var isDestroyView = false

    override fun onAttach(context: Context) {
        super.onAttach(context)
        baseActivity = activity as RouterActivity
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        isDestroyView = false
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onStart() {
        super.onStart()
        //通过SharedFlowBus观察UserBean的变化，从而通知页面刷新
        SharedFlowBus.on(UserBean::class.java).observe(this) { userBean ->
            if (!isDestroyView) {
                onUserStatusUpdate(userBean)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        hideInputMethod()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        isDestroyView = true
    }

    override fun onFirstLoad() {}

    /**
     * 用户状态更新方法
     *      当UserBean发生变化时该方法调用
     */
    open fun onUserStatusUpdate(userBean: UserBean) {}

    fun showDialog(){

    }

    fun dismissDialog(){

    }

    private fun hideInputMethod() {
        val inputMethodManager =
            baseActivity.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
        val view = baseActivity.currentFocus ?: return
        inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
    }
}